package com.cold.demo.web.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.*;
import java.io.File;
import java.io.IOException;

/**
 * @Author x c
 * @Email 378661553@qq.com
 * @Date Created in 2020/1/2 10:22
 * 用于调用打印机打印指定pdf文件
 */
public class PrinterUtil {

    private static final String PAGE_SIZE_A3 = "A3";
    private static final String PAGE_SIZE_A4 = "A4";


    /**
     * @param pdfFleUrl   pdf文件路径
     * @param pageSize    页面大小 A3,A4
     * @param printerName 打印机的名称
     * @throws Exception
     */
    public static void print(String pdfFleUrl, String pageSize, String printerName) throws IOException, PrinterException, ParameterException {
        File file = new File(pdfFleUrl);
        // 读取pdf文件
        PDDocument document = PDDocument.load(file);
        PrintService[] printServices = PrinterJob.lookupPrintServices();
        Assert.isNull(printServices, "无可用打印机");
        // 遍历所有打印机的名称
        PrintService canUsePs = null;
        for (PrintService ps : printServices) {
            String psName = ps.toString();
            // 选用指定打印机
            if (psName.equals(printerName)) {
                canUsePs = ps;
                break;
            }
        }
        Assert.isNull(canUsePs, "未找到指定的打印机名称：" + printerName);
        PageFormat pageFormat = new PageFormat();
        //PageFormat.PORTRAIT、正常打印
        //PageFormat.LANDSCAPE、横向打印
        pageFormat.setOrientation(PageFormat.LANDSCAPE);
        pageFormat.setPaper(getPaper(pageSize));

        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, document.getNumberOfPages());

        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintService(canUsePs);
        job.setPageable(book);
        // 开始打印
        job.print();
    }

    public static Paper getPaper(String pageSize) {
        Paper paper = new Paper();
        // 默认为A4纸张，对应像素宽和高分别为 595, 848
        //当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842， A3 1191*842
        int width;
        int height;
        //A3
        if (PAGE_SIZE_A3.equals(pageSize)) {
            width = 842;
            height = 1191;
        }else if (PAGE_SIZE_A4.equals(pageSize)){
            width = 595;
            height = 848;
        }else {
            ParameterException e = new ParameterException();
            e.setMsg("pageSize 参数错误,只支持A3/A4");
            throw e;
        }
        // 设置边距，单位是像素，10mm边距，对应 28px
        int marginLeft = 10;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        paper.setSize(width, height);
        // 下面一行代码，解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }

}
